//
//  HHFormSelectorCell.m
//  Pod
//
//  Created by chun.chen on 2018/3/1.
//  Copyright © 2018年 cc. All rights reserved.
//  申请表单选择类型 cell


#import "HHFormSelectorCell.h"
#import "HHFormSDKPublic.h"
#import "XLForm.h"
#import "NSArray+XLFormAdditions.h"
#import "NSObject+XLFormAdditions.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#import <Masonry/Masonry.h>
#pragma clang diagnostic pop



@interface HHFormSelectorCell() <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *descLab;

@end

@implementation HHFormSelectorCell

+ (void)load
{
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormSelectorCell class] forKey:HHFormRowDescriptorTypeSelectAction];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormSelectorCell class] forKey:HHFormRowDescriptorTypeSelectPicker];
    [XLFormViewController.cellClassesForRowDescriptorTypes setObject:[HHFormSelectorCell class] forKey:HHFormRowDescriptorTypeMultipleSelector];
}
-(NSString *)valueDisplayText
{
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeMultipleSelector]){
        if (!self.rowDescriptor.value || [self.rowDescriptor.value count] == 0){
            return self.rowDescriptor.noValueDisplayText;
        }
        if (self.rowDescriptor.valueTransformer){
            NSAssert([self.rowDescriptor.valueTransformer isSubclassOfClass:[NSValueTransformer class]], @"valueTransformer is not a subclass of NSValueTransformer");
            NSValueTransformer * valueTransformer = [self.rowDescriptor.valueTransformer new];
            NSString * tranformedValue = [valueTransformer transformedValue:self.rowDescriptor.value];
            if (tranformedValue){
                return tranformedValue;
            }
        }
        NSMutableArray * descriptionArray = [NSMutableArray arrayWithCapacity:[self.rowDescriptor.value count]];
        for (id option in self.rowDescriptor.selectorOptions) {
            NSArray * selectedValues = self.rowDescriptor.value;
            if ([selectedValues formIndexForItem:option] != NSNotFound){
                if (self.rowDescriptor.valueTransformer){
                    NSAssert([self.rowDescriptor.valueTransformer isSubclassOfClass:[NSValueTransformer class]], @"valueTransformer is not a subclass of NSValueTransformer");
                    NSValueTransformer * valueTransformer = [self.rowDescriptor.valueTransformer new];
                    NSString * tranformedValue = [valueTransformer transformedValue:option];
                    if (tranformedValue){
                        [descriptionArray addObject:tranformedValue];
                    }
                }
                else{
                    [descriptionArray addObject:[option displayText]];
                }
            }
        }
        return [descriptionArray componentsJoinedByString:@", "];
    }
    if (!self.rowDescriptor.value){
        return self.rowDescriptor.noValueDisplayText;
    }
    if (self.rowDescriptor.valueTransformer){
        NSAssert([self.rowDescriptor.valueTransformer isSubclassOfClass:[NSValueTransformer class]], @"valueTransformer is not a subclass of NSValueTransformer");
        NSValueTransformer * valueTransformer = [self.rowDescriptor.valueTransformer new];
        NSString * tranformedValue = [valueTransformer transformedValue:self.rowDescriptor.value];
        if (tranformedValue){
            return tranformedValue;
        }
    }
    return self.rowDescriptor.displayTextValue;
}
-(UIView *)inputView
{
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]){
        return self.pickerView;
    }
    return [super inputView];
}

-(BOOL)formDescriptorCellCanBecomeFirstResponder
{
    return (!self.rowDescriptor.isDisabled && ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]));
}

-(BOOL)formDescriptorCellBecomeFirstResponder
{
    return  [self becomeFirstResponder];
}

- (BOOL)canBecomeFirstResponder
{
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]){
        return YES;
    }
    return [super canBecomeFirstResponder];
}
#pragma mark - XLFormDescriptorCell

+ (CGFloat)formDescriptorCellHeightForRowDescriptor:(XLFormRowDescriptor *)rowDescriptor
{
    return 50;
}
-(void)configure
{
    [super configure];
    
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    [self.contentView addSubview:self.asteriskLab];
    [self.contentView addSubview:self.titleLab];
    [self.contentView addSubview:self.descLab];

    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(self.contentView);
    }];
    [self.descLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-1);
        make.centerY.mas_equalTo(self.contentView);
        //默认titleLable.right+30
        make.left.mas_equalTo(self.titleLab.mas_right).mas_offset(25);
    }];
    [self.asteriskLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.titleLab.mas_left).offset(-1);
        make.centerY.mas_equalTo(self.contentView);
    }];
}
-(void)update
{
    [super update];
    //设置 accessoryType
    if (self.rowDescriptor.indicatorImage == nil) {
        //未自定义指示器图片
        if (self.rowDescriptor.accessoryType) {
            self.accessoryType = (UITableViewCellAccessoryType)[self.rowDescriptor.accessoryType integerValue];
        } else {
            //默认展示箭头指示器
            self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    //更新 title 约束
    self.titleLab.text = self.rowDescriptor.title;
    CGFloat kTitleWidth = [NSString bc_autoWidth:self.titleLab.text stringFont:self.titleLab.font];
    [self.titleLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.contentView.mas_height);
        make.width.mas_equalTo(kTitleWidth+5);
    }];
    if (self.rowDescriptor.titleLeft>0) {
        [self.titleLab mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.rowDescriptor.titleLeft);
        }];
    }
    self.asteriskLab.hidden = !self.rowDescriptor.required;
    //更新 desc 约束
    if (self.rowDescriptor.textFont) {
        self.descLab.font = self.rowDescriptor.textFont;
    }
    if (self.rowDescriptor.textColor) {
        self.descLab.textColor = self.rowDescriptor.textColor;
    }
    if (self.rowDescriptor.textAlignment) {
        self.descLab.textAlignment = [self.rowDescriptor.textAlignment intValue];
    }
    if (self.rowDescriptor.textLeft>0) {
        [self.descLab mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-1);
            make.centerY.mas_equalTo(self.contentView);
            make.left.mas_equalTo(self.rowDescriptor.textLeft);
        }];
    }
    [self setupDescLabelValue];
}
-(void)formDescriptorCellDidSelectedWithFormController:(XLFormViewController *)controller
{
    if (self.rowDescriptor.action.formBlock){
        self.rowDescriptor.action.formBlock(self.rowDescriptor);
    }
    else if (self.rowDescriptor.action.formSelector){
        [controller performFormSelector:self.rowDescriptor.action.formSelector withObject:self.rowDescriptor];
    }
    else if ([self.rowDescriptor.action.formSegueIdentifier length] != 0){
        [controller performSegueWithIdentifier:self.rowDescriptor.action.formSegueIdentifier sender:self.rowDescriptor];
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]){
//        [controller.tableView selectRowAtIndexPath:nil animated:YES scrollPosition:UITableViewScrollPositionNone];
    }
    else if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeMultipleSelector]) {
        NSAssert(self.rowDescriptor.selectorOptions, @"selectorOptions property shopuld not be nil");
        UIViewController * controllerToPresent = nil;
        XLFormOptionsViewController * optionsViewController = nil;
        if ((controllerToPresent = [self controllerToPresent])){
            optionsViewController = (XLFormOptionsViewController *)controllerToPresent;
        } else {
            optionsViewController = [[XLFormOptionsViewController alloc] initWithStyle:UITableViewStyleGrouped titleHeaderSection:nil titleFooterSection:nil];
        }
        optionsViewController.rowDescriptor = self.rowDescriptor;
        optionsViewController.title = self.rowDescriptor.selectorTitle;
        [controller.navigationController pushViewController:optionsViewController animated:YES];
    }
    else if (self.rowDescriptor.action.formSegueClass){
        UIViewController * controllerToPresent = [self controllerToPresent];
        NSAssert(controllerToPresent, @"either rowDescriptor.action.viewControllerClass or rowDescriptor.action.viewControllerStoryboardId or rowDescriptor.action.viewControllerNibName must be assigned");
        UIStoryboardSegue * segue = [[self.rowDescriptor.action.formSegueClass alloc] initWithIdentifier:self.rowDescriptor.tag source:controller destination:controllerToPresent];
        [controller prepareForSegue:segue sender:self.rowDescriptor];
        [segue perform];
    }
    else{
        UIViewController * controllerToPresent = [self controllerToPresent];
        if (controllerToPresent){
            if ([controllerToPresent conformsToProtocol:@protocol(XLFormRowDescriptorViewController)]){
                ((UIViewController<XLFormRowDescriptorViewController> *)controllerToPresent).rowDescriptor = self.rowDescriptor;
            }
            if (controller.navigationController == nil || [controllerToPresent isKindOfClass:[UINavigationController class]] || self.rowDescriptor.action.viewControllerPresentationMode == XLFormPresentationModePresent){
                [controller presentViewController:controllerToPresent animated:YES completion:nil];
            }
            else{
                [controller.navigationController pushViewController:controllerToPresent animated:YES];
            }
        }
        
    }
}
-(void)highlight
{
    [super highlight];
}

-(void)unhighlight
{
    [super unhighlight];
}
- (void)formDescriptorDidDone
{
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]){
        NSInteger index = [self.pickerView selectedRowInComponent:0];
        if (index > 0) {
            return;
        }
        
        if (self.rowDescriptor.selectorOptions.count > 0) {
            self.rowDescriptor.value = [self.rowDescriptor.selectorOptions objectAtIndex:0];
            [self setupDescLabelValue];
            [self setNeedsLayout];
        }
    }
}

-(BOOL)showBottomSplitLine {
    return YES;
}

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (self.rowDescriptor.valueTransformer){
        NSAssert([self.rowDescriptor.valueTransformer isSubclassOfClass:[NSValueTransformer class]], @"valueTransformer is not a subclass of NSValueTransformer");
        NSValueTransformer * valueTransformer = [self.rowDescriptor.valueTransformer new];
        NSString * tranformedValue = [valueTransformer transformedValue:[[self.rowDescriptor.selectorOptions objectAtIndex:row] valueData]];
        if (tranformedValue){
            return tranformedValue;
        }
    }
    return [[self.rowDescriptor.selectorOptions objectAtIndex:row] displayText];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([self.rowDescriptor.rowType isEqualToString:HHFormRowDescriptorTypeSelectPicker]){
        if (row < self.rowDescriptor.selectorOptions.count) {
            self.rowDescriptor.value = [self.rowDescriptor.selectorOptions objectAtIndex:row];
            [self setupDescLabelValue];
            [self setNeedsLayout];
        }
    }
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.rowDescriptor.selectorOptions.count;
}
#pragma mark - Getter
-(UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] init];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        NSInteger selectedIndex = [self selectedIndex];
        if (selectedIndex>=0) {
            [_pickerView selectRow:selectedIndex inComponent:0 animated:NO];
        }
    }
    return _pickerView;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.font = BCComConfig.config.bcFont(16);
        _titleLab.textColor = BCComConfig.config.blackColor;
    }
    return _titleLab;
}
- (UILabel *)descLab {
    if (!_descLab) {
        _descLab = [[UILabel alloc] init];
        _descLab.font = BCComConfig.config.bcFont(16);
        _descLab.textAlignment = NSTextAlignmentRight;
        _descLab.textColor = BCComConfig.config.blackColor;
    }
    return _descLab;
}
#pragma mark - Helpers
- (void)setupDescLabelValue {
    NSString *displayText = [self valueDisplayText];
    if (displayText.length>0) {
        //有text
        self.descLab.text = [self valueDisplayText];
        self.descLab.textColor = self.rowDescriptor.value ? BCComConfig.config.blackColor : kBCRGBStrColor(BCComConfig.config.setting[@"bc_placeholderColor"]);
    } else if(self.rowDescriptor.textPlaceholder.length>0){
        //无text，有占位符
        self.descLab.text = self.rowDescriptor.textPlaceholder;
        self.descLab.textColor = kBCRGBStrColor(BCComConfig.config.setting[@"bc_placeholderColor"]);
    }
}
-(NSInteger)selectedIndex
{
    if (self.rowDescriptor.value){
        for (id option in self.rowDescriptor.selectorOptions){
            if ([[option valueData] isEqual:[self.rowDescriptor.value valueData]]){
                return [self.rowDescriptor.selectorOptions indexOfObject:option];
            }
        }
    }
    return -1;
}
-(UIViewController *)controllerToPresent
{
    if (self.rowDescriptor.action.viewControllerClass){
        return [[self.rowDescriptor.action.viewControllerClass alloc] init];
    }
    else if ([self.rowDescriptor.action.viewControllerStoryboardId length] != 0){
        UIStoryboard * storyboard =  [self storyboardToPresent];
        NSAssert(storyboard != nil, @"You must provide a storyboard when rowDescriptor.action.viewControllerStoryboardId is used");
        return [storyboard instantiateViewControllerWithIdentifier:self.rowDescriptor.action.viewControllerStoryboardId];
    }
    else if ([self.rowDescriptor.action.viewControllerNibName length] != 0){
        Class viewControllerClass = NSClassFromString(self.rowDescriptor.action.viewControllerNibName);
        NSAssert(viewControllerClass, @"class owner of self.rowDescriptor.action.viewControllerNibName must be equal to %@", self.rowDescriptor.action.viewControllerNibName);
        return [[viewControllerClass alloc] initWithNibName:self.rowDescriptor.action.viewControllerNibName bundle:nil];
    }
    return nil;
}

-(UIStoryboard *)storyboardToPresent
{
    if ([self.formViewController respondsToSelector:@selector(storyboardForRow:)]){
        return [self.formViewController storyboardForRow:self.rowDescriptor];
    }
    if (self.formViewController.storyboard){
        return self.formViewController.storyboard;
    }
    return nil;
}

@end

